import { _decorator, log, math, sys } from 'cc';
import { losTools } from '../Tools/losTools';
import { losChannel } from '../SDK/losChannel';
const { ccclass, property } = _decorator;

export class StaminaSystem {
    private static _instance: StaminaSystem;

    public static get instance(): StaminaSystem {
        if (!this._instance) {
            this._instance = new StaminaSystem();
        }
        return this._instance;
    }

    private _stamina: number = 3;
    private _maxStamina: number = 10;
    private _lastUpdateTime: number;
    private _isInfiniteStamina: boolean = false;
    private _infiniteStaminaEndTime: number = 0;

    private constructor() {
        const chName = losChannel.instance().channel;
        switch (chName) {
            case 'ks':
                this._maxStamina = 10;
                break;
            case 'ks2':
            case 'ks3':
                this._maxStamina = 20;
                break
            default:
                this._maxStamina = 20;
                break;
        }
        this.loadStamina();
        this.calculateOfflineStaminaRecovery(); // 计算离线期间恢复的体力
        const infiniteStaminaEndTime = sys.localStorage.getItem('infiniteStaminaEndTime');
        if (infiniteStaminaEndTime) {
            this._infiniteStaminaEndTime = parseInt(infiniteStaminaEndTime);
            if (Date.now() < this._infiniteStaminaEndTime) {
                this._isInfiniteStamina = true;
            }
        }
        this._lastUpdateTime = Date.now();
    }

    private loadStamina(): void {
        const stamina = sys.localStorage.getItem('stamina');
        if (stamina) {
            this._stamina = parseInt(stamina);
        }
        else {
            this._stamina = this._maxStamina;
        }
    }

    private saveStamina(): void {
        sys.localStorage.setItem('stamina', this._stamina.toString());
    }

    // 计算离线期间应该恢复的体力值
    private calculateOfflineStaminaRecovery(): void {
        const lastSavedTime = sys.localStorage.getItem('lastSavedTime');
        if (lastSavedTime) {
            const lastSavedTimestamp = parseInt(lastSavedTime);
            const timeOffline = Date.now() - lastSavedTimestamp;
            const staminaRecovered = Math.floor(timeOffline / (60000)); // 每分钟恢复1点体力
            this.addStaminaFromTime(staminaRecovered);
        }
        sys.localStorage.setItem('lastSavedTime', Date.now().toString()); // 更新保存时间
    }

    public update(deltaTime: number): void {
        if (this._isInfiniteStamina && Date.now() > this._infiniteStaminaEndTime) {
            this._isInfiniteStamina = false;
        }
        if (!this._isInfiniteStamina && Date.now() - this._lastUpdateTime >= 60000) {
            this._lastUpdateTime = Date.now();
            this.addStaminaFromTime(1);
        }
        this.getRecoveryLeftTime()
    }
    /**
     * getRecoveryLeftTime
     */
    public getRecoveryLeftTime() {
        let t = Math.abs(Math.round((this._lastUpdateTime - Date.now()) / 1000))
        //log("剩余多少秒恢复体力：" + losTools.formatSeconds(60 - t, false))
        return this._stamina >= this._maxStamina || this._isInfiniteStamina ? '已满' : losTools.formatSeconds(60 - t, false)
    }

    private addStaminaFromTime(amount: number): void {
        if (this._stamina < this._maxStamina) {
            this._stamina = math.bits.min(this._stamina + amount, this._maxStamina);
            log('增加了' + amount + '点体力，当前体力值：' + this._stamina + '点。上限值：' + this._maxStamina + '点。');
        }


        this.saveStamina();
        sys.localStorage.setItem('lastSavedTime', Date.now().toString()); // 更新保存时间

    }

    public addStamina(amount: number): void {
        this._stamina += amount;
        this.saveStamina();
    }

    public reduceStamina(amount: number): void {
        if (this._isInfiniteStamina) return;

        this._stamina -= amount;
        if (this._stamina < 0) {
            this._stamina = 0;
        }
        this.saveStamina();
    }

    public getStamina(): number {
        return this._isInfiniteStamina ? Infinity : this._stamina;
    }

    public setInfiniteStamina(durationHours: number): void {
        this._isInfiniteStamina = true;
        this._infiniteStaminaEndTime = Date.now() + durationHours * 3600000;
        sys.localStorage.setItem('infiniteStaminaEndTime', this._infiniteStaminaEndTime.toString()); // 更新保存时间
    }

    public isInfiniteStamina(): boolean {
        return this._isInfiniteStamina;
    }
}

// @ccclass('StaminaSystemComponent')
// export class StaminaSystemComponent extends Component {
//     start() {
//         // 在组件启动时计算离线期间的体力恢复
//         StaminaSystem.instance.calculateOfflineStaminaRecovery();
//     }

//     update(deltaTime: number) {
//         StaminaSystem.instance.update(deltaTime);
//     }
// }
